#include "VFolderData.h"
#include "VFunctions.h"

#include <QDir>
#include <QFileInfo>
#include <QDateTime>

VFolderData::VFolderData(QString path)
{

    _path = path;
    traversal();
}

VFolderData::~VFolderData()
{
    foreach(VFolderData* ptr, _folder_list)
    {
        delete ptr;
    }
}

QStringList VFolderData::matching(QString input)
{
    QStringList result;
    foreach(QString name, _file_list)
    {
        if(VFunctions::matching_string(name, input))
        {
            result.append(name);
        }

    }

    foreach(VFolderData* ptr, _folder_list)
    {
        result += ptr->matching(input);
    }

    return result;
}

void VFolderData::modify_testing()
{
    if(QFileInfo(_path).lastModified().toTime_t() > _last_time)
    {
        _file_list.clear();
        foreach(VFolderData* ptr, _folder_list)
        {
            delete ptr;
        }
        _folder_list.clear();

        traversal();
    }
}

QString VFolderData::find_file(QString path)
{
    QString result;
    foreach(QString name, _file_list)
    {
        if(path == name)
        {
            return _path + "/" + name;
        }

    }

    foreach(VFolderData* ptr, _folder_list)
    {
        result = ptr->find_file(path);
        if(result.length() > 0)
        {
            break;
        }
    }

    return result;
}

void VFolderData::traversal()
{
    _last_time = QFileInfo(_path).lastModified().toTime_t();

    QDir dir(_path);
    foreach(QFileInfo mfi ,dir.entryInfoList())
    {
      if(mfi.isFile())
      {
          _file_list.append(mfi.fileName());
      }else
      {
          if(mfi.fileName()=="." || mfi.fileName() == "..")
              continue;

          _folder_list.append(new VFolderData(mfi.absoluteFilePath()));
      }
    }
}
